﻿import GameConfig from "./GameConfig";
import ConstStrings from "./datas/strings";
import SelectItemView from "./SelectItemView"
import CandidateItemView from "./CandidateItemView"
import ScreenPositionUtil from "./ScreenPositionUtil";

class Main {
	constructor() {
		GameConfig.nikeVersion = "aj4";
		//根据IDE设置初始化引擎
		this.onCreateCommand(GameConfig.width, GameConfig.height ,1)
	}

	setShoeVersionBeforeInit(inVersion) {
		GameConfig.nikeVersion = inVersion;
	}

	setGameData(inData) {
		GameConfig.gameData = inData;
	}

	onCreateCommand(inW,inH ,inPr) {
		GameConfig.width = inW * inPr;
		GameConfig.height = inH * inPr;
		GameConfig.inPr = inPr;
		Laya.Config.isAntialias=true;
		//根据IDE设置初始化引擎		
		if (window["Laya3D"]) Laya3D.init(GameConfig.width, GameConfig.height);
		else Laya.init(GameConfig.width, GameConfig.height, Laya["WebGL"]);
		Laya["Physics"] && Laya["Physics"].enable();
		Laya["DebugPanel"] && Laya["DebugPanel"].enable();
		Laya.stage.scaleMode = GameConfig.scaleMode;
		Laya.stage.screenMode = GameConfig.screenMode;
		// Laya.stage.alignV = GameConfig.alignV;
		// Laya.stage.alignH = GameConfig.alignH;

		Laya.stage.alignV = Laya.Stage.ALIGN_MIDDLE;
		Laya.stage.alignH = Laya.Stage.ALIGN_CENTER;
		//兼容微信不支持加载scene后缀场景
		Laya.URL.exportSceneToJson = GameConfig.exportSceneToJson;

		//打开调试面板（通过IDE设置调试模式，或者url地址增加debug=true参数，均可打开调试面板）
		if (GameConfig.debug || Laya.Utils.getQueryString("debug") == "true") Laya.enableDebugPanel();
		if (GameConfig.physicsDebug && Laya["PhysicsDebugDraw"]) Laya["PhysicsDebugDraw"].enable();
		if (GameConfig.stat) Laya.Stat.show();
		Laya.alertGlobalError(true);

		//激活资源版本控制，version.json由IDE发布功能自动生成，如果没有也不影响后续流程
		Laya.ResourceVersion.enable("version.json", Laya.Handler.create(this, this.onVersionLoaded), Laya.ResourceVersion.FILENAME_VERSION);

		
		this.selectedDatas = [{},{},{},{}];

		if(GameConfig.gameData != null) {
			this.candidateDatas = GameConfig.gameData.candidateList;
		} 
		else {
			GameConfig.gameData = ConstStrings.candidateImgDatas.find(element => {
				if(element.id == GameConfig.nikeVersion)
					return element;
			})
			this.candidateDatas = GameConfig.gameData.candidateList;	
		}


		this.selectedDataViews = [];
		this.selectedViewsNum = 4;

		this.viewSelectList = null;
		this.viewCandidateList = null;

		this.initScene();
	}

	onVersionLoaded() {
		//激活大小图映射，加载小图的时候，如果发现小图在大图合集里面，则优先加载大图合集，而不是小图
		Laya.AtlasInfoManager.enable("fileconfig.json", Laya.Handler.create(this, this.onConfigLoaded));
	}

	onConfigLoaded() {
		//加载IDE指定的场景
		GameConfig.startScene && Laya.Scene.open(GameConfig.startScene);
	}

	initScene() {
		ScreenPositionUtil.setStageWidthAndHeight(Laya.stage.width , Laya.stage.height);
		Laya.stage.bgColor = "#6f6f6f99";
		let loadList = [];
		loadList.push(GameConfig.gameData.atlas);
		loadList.push(ConstStrings.baseSrcPath);
		loadList.push(ConstStrings.tabSrcPath);

		Laya.loader.load(loadList, Laya.Handler.create(this, this.onAtlasLoaded));
	}

	onAtlasLoaded(){
		console.log("load ok")

		let titleMarginLeftRatio = 0.05;
		let titleMarginTopRatio = 0.14;
		let titleWidthRatio = 0.28;
		let titleImgWHRatio = 2.125

		this.pageTitleDotView = new Laya.Sprite();
		this.pageTitleDotView.width = ScreenPositionUtil.getPostionInStage(titleWidthRatio ,"x");
		this.pageTitleDotView.height = this.pageTitleDotView.width / titleImgWHRatio ;
		this.pageTitleDotView.pos(ScreenPositionUtil.getPostionInStage(titleMarginLeftRatio ,"x")  , ScreenPositionUtil.getPostionInStage(titleMarginTopRatio ,"y"));
		this.pageTitleDotView.loadImage(GameConfig.gameData.pageTitle);
		Laya.stage.addChild(this.pageTitleDotView);
		
		this.initSelectedBox();
		this.initCandidateBox();
	}

	initSelectedBox() {
		this.viewSelectList = new Laya.List();
		Laya.stage.addChild(this.viewSelectList);

		let viewSelectItemImg_W = ScreenPositionUtil.getPostionInStage(ConstStrings.viewSelectItemWidthRatio ,"x");
		let viewSelectItemImg_H = ScreenPositionUtil.getPostionInStage(ConstStrings.viewSelectItemWidthRatio ,"x") / ConstStrings.viewSelectItemImgWHRatio;


		this.viewSelectList.itemRender = SelectItemView;
		this.viewSelectList.repeatX = this.selectedViewsNum;
		this.viewSelectList.repeatY = 1;
		this.viewSelectList.x = Laya.stage.width - ScreenPositionUtil.getPostionInStage(ConstStrings.viewSelectListMarginRightRatio ,"x") 
			- (ScreenPositionUtil.getPostionInStage(ConstStrings.viewSelectItemWidthRatio ,"x") * this.selectedViewsNum);
		this.viewSelectList.y = ScreenPositionUtil.getPostionInStage(ConstStrings.viewSelectListMarginTopRatio ,"y");

		this.viewSelectLine = new Laya.Sprite;
		Laya.stage.addChild(this.viewSelectLine);
		this.viewSelectLine.pos(0, this.viewSelectList.y + viewSelectItemImg_H);
		this.viewSelectLine.graphics.drawRect(ScreenPositionUtil.getPostionInStage(ConstStrings.viewSelectListMarginRightRatio ,"x") , 0,
			Laya.stage.width - ScreenPositionUtil.getPostionInStage(ConstStrings.viewSelectListMarginRightRatio ,"x") * 2 , 2, "#000000" )

		/**
		 * 选中列表更新
		 * @param {*} cell 
		 * @param {*} index 
		 */
		var updateItem = function (cell, index) {
			console.log("select updateItem " + index)
			
			let isFirstEmpty = false;
			if( (!this.selectedDatas[index].src && index == 0) || ( index > 0 && !this.selectedDatas[index].src && this.selectedDatas[index - 1].src) )
				isFirstEmpty = true;

			cell.setSrcImg(cell.dataSource.src, isFirstEmpty);
		};

		/**
		 * 选中列表中item被选中
		 * @param {*} index 
		 */
		var onSelect = function (index) {
			console.log("当前选择的索引：" + index);
		}

		this.viewSelectList.selectHandler = new Laya.Handler(this, onSelect);
		this.viewSelectList.renderHandler = new Laya.Handler(this, updateItem);

		this.viewSelectList.array = this.selectedDatas;
	}

	initCandidateBox() {
		this.viewCandidateList = new Laya.List();
		Laya.stage.addChild(this.viewCandidateList);
		this.viewCandidateList.itemRender = CandidateItemView;
		this.viewCandidateList.repeatX = 2;
		this.viewCandidateList.repeatY = 4;

		this.viewCandidateList.selectEnable = true;

		this.viewCandidateList.x = ScreenPositionUtil.getPostionInStage(ConstStrings.boxMarginLeftRatio ,"x");
		// this.viewCandidateList.y = ScreenPositionUtil.getPostionInStage(ConstStrings.boxMarginTopRatio ,"y");
		this.viewCandidateList.y = this.viewSelectLine.y + ConstStrings.boxMarginTopDis * GameConfig.inPr;
		ConstStrings.candidateStartY = this.viewSelectLine.y;

		/**
		 * 选中列表更新
		 * @param {*} cell 
		 * @param {*} index 
		 */
		var updateItem = function (cell, index) {
			console.log("updateItem " + index)
			cell.setSrcImg(cell.dataSource.src);
			cell.isSelectImgVisible();
		};

		/**
		 * 选中列表中item被选中
		 * @param {*} index 
		 */
		var onSelect = function (e, index) {
			if (e.type != "mouseup")
				return;

			let tempCell = this.viewCandidateList.getCell(index);

			// 已选中完毕 数据完成
			if (!tempCell.dataSource.isSelected && this.selectedDatas.length >= this.selectedViewsNum * 2) {
				return;
			}
			
			// 是否正确答案
			let tempIsRight = tempCell.dataSource.isRight;

			// 是否已在选中列表里
			let temp = this.selectedDatas.findIndex(obj => obj.id == tempCell.dataSource.id);
			let tempIsExit = false;
			if (temp >= 0)
				tempIsExit = true;

			
			if(tempIsExit) {
				// 如果已被选中过：选中列表删掉一个
				// this.selectedDatas.splice(temp, 1);
				// 如果已被选中过：备选列表设置未选中
				// tempCell.dataSource.isSelected = false;
				// tempCell.dataSource.needAni = true;
				// tempCell.dataSource.needAniType = "unselect";
			} else {
				// 如果没有被选中 且答案正确
				if(tempIsRight) {
					// this.selectedDatas.unshift(tempCell.dataSource);
					let tempIndex = -1;
					for(let i = 0 ; i < this.selectedDatas.length; i++) {
						if(!this.selectedDatas[i].id) {
							this.selectedDatas.splice(i, 0, tempCell.dataSource);
							tempIndex = i;
							break;
						}
					}

					tempCell.dataSource.isSelected = true;
					tempCell.dataSource.needAni = true;
					tempCell.dataSource.needAniType = "select";

					let tempTo = this.viewSelectList.getCell(tempIndex).getSelectAniInfo();
					let tempFrom = this.viewCandidateList.getCell(index).getShoeAniInfo();

					this.aniFlyShoeToSelectPosition(tempFrom.src , tempFrom , tempTo);

				} else {
					tempCell.dataSource.isSelected = false;
					tempCell.dataSource.needAni = true;
					tempCell.dataSource.needAniType = "wrong";
				}
			}

			this.viewSelectList.refresh();
			this.viewCandidateList.refresh();

			if(this.selectedDatas.length >= this.selectedViewsNum * 2) {
				// todo:完成选择
			}
		}

		this.viewCandidateList.mouseHandler = new Laya.Handler(this, onSelect);
		this.viewCandidateList.renderHandler = new Laya.Handler(this, updateItem);
		this.viewCandidateList.array = this.candidateDatas;

		this.flyShoeView = new Laya.Sprite;
		Laya.stage.addChild(this.flyShoeView);
		this.flyShoeView.alpha = 1;
	}

	aniFlyShoeToSelectPosition(shoePicSrc, fromInfo, endInfo) { 
		this.flyShoeView.loadImage(shoePicSrc);
		this.flyShoeView.alpha = 1;

		this.flyShoeView.pos(fromInfo.x ,fromInfo.y);
		this.flyShoeView.width = fromInfo.width;
		this.flyShoeView.height = fromInfo.height;
		this.flyShoeView.rotation = 0;


		Laya.Tween.to(this.flyShoeView, { x: endInfo.x ,y:endInfo.y }, 500, Laya.Ease.strongIn);
		Laya.Tween.to(this.flyShoeView, { width: endInfo.width , height: endInfo.height}, 300, Laya.Ease.strongIn);
		Laya.Tween.to(this.flyShoeView, { rotation: -30 }, 600, Laya.Ease.strongIn);
		Laya.Tween.to(this.flyShoeView, { alpha: 0 }, 550, Laya.Ease.strongIn);


	}

	resetSceneState() {
		this.selectedDatas = [{}, {}, {}, {}];
		this.candidateDatas.forEach(e => {
			e.isSelected = false;
			e.needAni = true;
			e.needAniType = "unselect";
		});

		this.viewSelectList.array = this.selectedDatas;
		this.viewCandidateList.array = this.candidateDatas;

		this.viewSelectList.refresh();
		this.viewCandidateList.refresh();
	}
}
//激活启动类
let g_main = new Main();
